import axios from 'axios';
import awaitWrap from '../awaitWrap';

async function multiThreadGet(urlList: string[], count = 10) {

    let sum = urlList.length;
    let responseArr = urlList.map(url => {
        return {url, status: '未查询'};
    });

    // 尝试发起 三 轮请求
    for (let tryIndex = 0; tryIndex < 1; tryIndex++) {
        let map = new Map();

        for (let responseIndex = 0; responseIndex < responseArr.length; responseIndex++) {
            const responseItem = responseArr[responseIndex];

            if (map.size >= count) {
                await Promise.race(Array.from(map.values()));
            }

            map.set(responseItem.url,
                axios.get(responseItem.url)
                    .then((AxiosResponse) => {
                        responseItem.status = 'success';
                        return AxiosResponse;
                    })
                    .catch((AxiosResponse) => {
                        if (AxiosResponse.response.status === 404) {
                            responseItem.status = 'Not Found';
                        } else if (AxiosResponse.response.status === 401) {
                            responseItem.status = 'Not Authorized';
                        } else if (AxiosResponse.response.status === 422) {
                            responseItem.status = 'MapBox 服务器暂时无此瓦片';
                        } else {
                            responseItem.status = 'error';
                        }
                    })
                    .finally(() => {
                        if (responseIndex % 50 === 0) {
                            console.log('已请求', responseIndex, '/', sum, responseIndex / sum * 100 + '%');
                        }
                        map.delete(responseItem.url);
                    }));

        }
        await Promise.all(Array.from(map.values()));
    }

    return responseArr;
}


export default multiThreadGet;
